package com.maniksinghal4686.timedsilencer;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Vibrator;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class TimedSilenceProvider extends AppWidgetProvider {

	static final String LOG = "mylog";
	
	static final String USER_CLICK = "com.maniksinghal4686.timedsilencer.USER_CLICK";
	static final String USER_CHOICE = "com.maniksinghal4686.timedsilencer.USER_CHOICE";
	static final String SERVICE_EVENT = "com.maniksinghal4686.timedsilencer.SERVICE_EVENT";
	
	static final String USER_MILLIS = "com.maniksinghal4686.timedsilencer.USER_MINUTES";
	static final String USER_MODE = "com.maniksinghal4686.timedsilencer.USER_MODE";
	static final String ALARM_CANCEL = "com.maniksinghal4686.timedsilencer.ALARM_CANCEL";
	
	
	private void cancelAlarm(Context context) {
		Intent service_intent = new Intent(context, getClass());
        service_intent.setAction(SERVICE_EVENT);
        PendingIntent pending =  PendingIntent.getBroadcast(context, 0, service_intent, PendingIntent.FLAG_CANCEL_CURRENT);
    	
        AlarmManager alm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alm.cancel(pending);
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		
		AppWidgetManager appmgr;
		ComponentName thisWidget = new ComponentName(context.getPackageName(),
		        TimedSilenceProvider.class.getName());
		appmgr = AppWidgetManager.getInstance(context);
		int[] allWidgetIds = appmgr.getAppWidgetIds(thisWidget);
		
		Log.v(LOG, "Received intent: " + intent);
		if (intent.getAction().equals(SERVICE_EVENT)) {
			// Event from the AlarmManager, triggering completion of silence/vibration period
			Log.v(LOG, "Got the service event");
			
			// Time up => switch back to normal mode
			AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
		    am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
		    Log.v(LOG, "Changed Ringer mode to NORMAL");
			
			// Update the view
			for (int widgetId : allWidgetIds) {
				updateSilencerView(widgetId, context, appmgr, null);
			}
			
			
		} else if (intent.getAction().equals(USER_CHOICE)) {
			
			int state = intent.getIntExtra(USER_MODE, AudioManager.RINGER_MODE_NORMAL);
			if (state == AudioManager.RINGER_MODE_NORMAL) {
				// no change
				return;
			}
			
			// User asked us to switch to Silent/Vibrate mode
			AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
		    am.setRingerMode(state);
		    
		    // Start the service providing it the time to wait
		    long millis = intent.getLongExtra(USER_MILLIS, 0);
		    String target_time = null;
			
		    

	        if (millis > 0) {
	        	// Notify AlarmManager to poke us after service_minutes.
		    	Intent service_intent = new Intent(context, getClass());
		        service_intent.setAction(SERVICE_EVENT);
		        PendingIntent pending =  PendingIntent.getBroadcast(context, 0, service_intent, PendingIntent.FLAG_CANCEL_CURRENT);
		    	
		        AlarmManager alm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		        
	        	// Silence/Vibration for a limited period
	        	Calendar cal = Calendar.getInstance();
		    	cal.setTimeInMillis(millis);
		    	
		    	/*
		    	 * The target time is hh:mm:ss. We tell user that we shall switch-back at hh:mm
		    	 * Remove the 'ss' part to stay consistent with what we say
		    	*/
		    	cal.add(Calendar.SECOND,  - (cal.get(Calendar.SECOND)));
		    	
		    	//target_time = new SimpleDateFormat("HH:mm").format(cal.getTime());
		    	target_time = new SimpleDateFormat("HH:mm", java.util.Locale.getDefault()).format(cal.getTime());
		    	
		    	alm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pending);
	        }
	    	
	    	//// Update the view
		    for (int widgetId : allWidgetIds) {
		    	updateSilencerView(widgetId, context, appmgr, target_time);
		    }
		    
		    // vibrate if we just switched to Vibrate mode
		    if (state == AudioManager.RINGER_MODE_VIBRATE) {
		    	Vibrator v = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
			    v.vibrate(500);	
		    }
		    			
		} else if (intent.getAction().equals(USER_CLICK)) {
			
			// User clicked us.
						
			int state = getAudioState(context);
			
			// If not in Normal mode, then switch to normal
			if (state != AudioManager.RINGER_MODE_NORMAL) {
			    AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
			    am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
			    
			    // Cancel any scheduled alarm
			    cancelAlarm(context);
			    
			    // Toast
			    Toast toast = Toast.makeText(context,  "Normal mode set",  Toast.LENGTH_SHORT);
			    toast.show();
			    
			    // Set our state to RINGER mode NORMAL
			    Log.v(LOG, "Changed audio_state to: Normal");
			    
			    // Update the view
			    for (int widgetId : allWidgetIds) {
			    	updateSilencerView(widgetId, context, appmgr, null);
			    }	
			} else {
				
				/*
				// Update view
				for (int widgetId : allWidgetIds) {
					updateSilencerView(widgetId, context, appmgr);
				}
				*/
				
				// Need to launch an activity for user to select vibrate/silent mode
				Intent i = new Intent(context, SilenceOptionsActivity.class);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(i);
			}
			
		} else {
		   Log.v(LOG, "Called onReceive1");
		   super.onReceive(context, intent);
		   Log.v(LOG, "Called onReceive2");
		}
	}
	
	/*
	private String get_audio_string2(int state) {
		switch (state) {
		case AudioManager.RINGER_MODE_NORMAL:
			return "N";
		case AudioManager.RINGER_MODE_SILENT:
			return "S";
		case AudioManager.RINGER_MODE_VIBRATE:
			return "V";
		default:
				return "U";
		}
	}
	
	private String get_audio_string() {
		return get_audio_string2(audio_state);
	}
	*/
	
	private int getAudioState(Context context) {
		AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
		return am.getRingerMode();
	}
	
	
	@Override
	public void onEnabled(Context context) {
		
		Log.v(LOG, "Called Enabled1");
		super.onEnabled(context);
		Log.v(LOG, "Called onEnabled2");
		
	}
	
	@Override
	public void onDisabled(Context context) {
		Log.v(LOG, "Called onDisabled");
	}
	
	protected PendingIntent getPendingSelfIntent(Context context, String action) {
        Intent intent = new Intent(context, getClass());
        intent.setAction(action);
        return PendingIntent.getBroadcast(context, 0, intent, 0);
    }
	
	private void updateSilencerView(int widget_id, Context context, AppWidgetManager appWidgetManager,
			String target_time) {
		RemoteViews view = new RemoteViews(context.getPackageName(),
		          R.layout.silence_layout);
		// Attach the SilenceOptionsActivity to the click event
		if (target_time != null) {
			view.setTextViewText(R.id.update, "(till " + target_time + ")");
		} else {
			view.setTextViewText(R.id.update, null);	
		}
		
		int state = getAudioState(context);
		switch(state) {
		case AudioManager.RINGER_MODE_NORMAL:
			view.setImageViewResource(R.id.widgetImage, R.drawable.normal);
			break;
		case AudioManager.RINGER_MODE_SILENT:
			view.setImageViewResource(R.id.widgetImage, R.drawable.silent);
			break;
		case AudioManager.RINGER_MODE_VIBRATE:
			view.setImageViewResource(R.id.widgetImage, R.drawable.vibrate);
			break;
		}
		
		view.setOnClickPendingIntent(R.id.update, getPendingSelfIntent(context, USER_CLICK));
		view.setOnClickPendingIntent(R.id.widgetImage, getPendingSelfIntent(context, USER_CLICK));
		appWidgetManager.updateAppWidget(widget_id, view);
	}
	
	@Override
	  public void onUpdate(Context context, AppWidgetManager appWidgetManager,
	      int[] appWidgetIds) {
		
		Log.v(LOG, "Called onUpdate1");
		
        ComponentName thisWidget = new ComponentName(context,
		        TimedSilenceProvider.class);
		    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
		    for (int widgetId : allWidgetIds) {
		    	updateSilencerView(widgetId, context, appWidgetManager, null);
				
		    }
		    
		    /*
		    Log.v(LOG, "Starting the service");
		    Intent intent = new Intent(context, SilenceTracker.class);
		    context.startService(intent);
		    */
		
		
		Log.v(LOG, "Called onUpdate2");
	}
}
